//
//  ShellCalculateChartView.m
//  ShellWallert
//
//  Created by lvzhao on 2019/10/3.
//  Copyright © 2019 VV. All rights reserved.
//

#import "ShellCalculateChartView.h"
#import "ShellNetworkCalculateViewModel.h"
#import "CMPopTipView.h"
#import "ShellCalculateModel.h"

/**
 *  视图的坐高度
 */
#define kViewHeight 445




@interface ShellCalculateChartView()

@property (nonatomic,strong) ShellNetworkCalculateViewModel *viewModel;


@property (nonatomic,strong) UIScrollView *scrollView;

/**y轴数组*/
@property (strong, nonatomic) NSArray * yLabels;

/**x轴数组*/
@property (strong, nonatomic) NSArray * xLabels;

/**最大值*/
@property (assign, nonatomic) CGFloat maxValue;

/**第一个点*/
@property (nonatomic, assign) CGPoint originPoint;
@property (nonatomic, assign) CGPoint lastPoint;
//coverBtns
@property (nonatomic,strong)NSMutableArray *coverBtns;

@end
@implementation ShellCalculateChartView

- (instancetype)initViewModel:(LZBaseViewModel *)viewModel
{
    self = [super init];
    if (self) {
        self.backgroundColor = COLOR_BACKGROUND;
        
        self.viewModel = (ShellNetworkCalculateViewModel *)viewModel;
        [self setupView];
    }
    return self;
}

#pragma mark - setupView
- (void)setupView{
    
    
    [self addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(45);
        make.height.mas_equalTo(kViewHeight);
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
    }];
    
    
    
    
    
    @weakify(self);
    [self.viewModel.reloadSubject subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        
        
        NSMutableArray *xLabels = [NSMutableArray arrayWithCapacity:0];
        NSMutableArray *yLabels = [NSMutableArray arrayWithCapacity:0];

        for (int i = 0; i < self.viewModel.dataArray.count; i++) {
            ShellCalculateModel *calculateModel = self.viewModel.dataArray[i];
            CGFloat hashRate = calculateModel.hashRate;
            [yLabels addObject:[NSString stringWithFormat:@"%f",hashRate]];
            
            [xLabels addObject:calculateModel.statisticalTime];
        }
        
        self.xLabels = xLabels;
        self.yLabels = yLabels;
        [self strokeChart];
    }];

}


// Y刻度
- (void)setYLabels:(NSArray *)yLabels{
    _yLabels = yLabels;
    
    //求出最大值 然后分三份 再加上一份的一半,  最大Y值
    CGFloat yValueMax = [[self.yLabels valueForKeyPath:@"@max.floatValue"] floatValue];
    yValueMax = yValueMax +  (yValueMax / 10);
    //分多少份
    CGFloat level = 0;
    if (yValueMax < 2){
        level = 0.2;
    } else if ((yValueMax >= 5 ) && (yValueMax < 10)){
        level = 10;
    } else {
        
        NSInteger maxLevel = yValueMax / 3;
        if(maxLevel%10 == 0){
            level = maxLevel;
        } else {
            NSString *lastOne = [[NSString stringWithFormat:@"%ld",(long)maxLevel] substringFromIndex:1];
            maxLevel = maxLevel + 10 - [lastOne integerValue];
        }
    }
    
    self.maxValue = level * 10;
    
    //线的间隔
    CGFloat yMarkLineInterval = (kViewHeight - 35 - 4)/10.0;

    for (NSInteger i = 0; i < 11; i ++) {

        UIImageView *lineView = [[UIImageView alloc] init];
        lineView.image = k_imageName(@"icon_xuxian");
        
        lineView.frame = CGRectMake(20, kViewHeight  - 35 - i *  (yMarkLineInterval + 1) + 45, K_SCREENWIDTH - 40, 1);
        [self insertSubview:lineView atIndex:0];
        
        UILabel *ymarkLab = [[UILabel alloc] initWithFrame:CGRectMake(20,lineView.y - 25,50,20)];
        ymarkLab.font = [UIFont systemFontOfSize:12];
        ymarkLab.textColor = UIColorHex(0x1666A0);
        //        字体倾斜
        //        markLab.transform = CGAffineTransformMakeRotation(-M_PI_4/2);
        ymarkLab.text = [NSString stringWithFormat:@"%f",level * i].saveDecimal;
        
        [self addSubview:ymarkLab];

    }
}



// X刻度
- (void)setXLabels:(NSArray *)xLabels{
    _xLabels = xLabels;
    
    CGFloat num = xLabels.count;
    CGFloat xLabelWidth = 40;
    //间隔
    CGFloat xLabInterval = (K_SCREENWIDTH - 40 - 5 * 40)/4.0;
    
    for (int i = 0; i < num; i++) {
    
        NSString *labelText = xLabels[i];
        UILabel * xlabel = [UILabel lz_labelWithText:labelText fontSize:k_textFont(12) color:UIColorHex(0x1666A0)];
        xlabel.frame = CGRectMake(i * (xLabInterval + 40) - 20, kViewHeight - 30, xLabelWidth, 20);
        xlabel.adjustsFontSizeToFitWidth = YES;
        xlabel.text = labelText;
        [self.scrollView addSubview:xlabel];
        
    }
    
    self.scrollView.contentSize = CGSizeMake((num - 1) * (xLabInterval + 40), 0);

 
}


- (void)strokeChart
{
    if(self.yLabels.count == 0)return;
    //划线
    CAShapeLayer *chartLine = [CAShapeLayer layer];
    chartLine.lineCap = kCALineCapRound;   //设置线条拐角帽的样式
    chartLine.lineJoin = kCALineJoinRound; //设置两条线连结点的样式
    chartLine.fillColor   = [[UIColor clearColor] CGColor];
    chartLine.lineWidth   = 3.0;
    chartLine.strokeEnd   = 0.0;
    [self.scrollView.layer addSublayer:chartLine];
    
    //线
    UIBezierPath *progressline = [UIBezierPath bezierPath];
    CGFloat firstValue = [[self.yLabels objectAtIndex:0] floatValue];
    CGFloat xPosition = 0;
    
    CGFloat percent = firstValue / self.maxValue;
    CGFloat yPosition =  (kViewHeight - 35 ) * (1 - percent);
    
    CGPoint firstPoint = CGPointMake(xPosition, yPosition);
    [progressline moveToPoint:firstPoint];
    [progressline setLineWidth:2.0];
    [progressline setLineCapStyle:kCGLineCapRound];
    [progressline setLineJoinStyle:kCGLineJoinRound];
    
    //遮罩层形状
    UIBezierPath *bezier1 = [UIBezierPath bezierPath];
    bezier1.lineCapStyle = kCGLineCapRound;
    bezier1.lineJoinStyle = kCGLineJoinMiter;
    [bezier1 moveToPoint:firstPoint];
    self.originPoint = firstPoint;       //记录原点
   
    
    CGPoint nextPoint = CGPointMake(0, 0);

    //间隔
    CGFloat xLabInterval = (K_SCREENWIDTH - 40 - 5 * 40)/4.0;
    NSInteger index = 0;
    for (NSString *valueString in self.yLabels) {
        
        CGFloat percent = [valueString floatValue] / self.maxValue;
        CGFloat yPosition =  (kViewHeight - 35)* (1 - percent);
        CGPoint point = CGPointMake(xPosition + index * (40 +xLabInterval), yPosition);
        
        if (index != 0) {
            
            [progressline addCurveToPoint:point controlPoint1:CGPointMake((point.x + nextPoint.x ) / 2, nextPoint.y) controlPoint2:CGPointMake(( point.x + nextPoint.x)/2, point.y)];
            [progressline moveToPoint:point];
            [bezier1 addCurveToPoint:point controlPoint1:CGPointMake((point.x + nextPoint.x) / 2, nextPoint.y) controlPoint2:CGPointMake((point.x + nextPoint.x)/2, point.y)];
        }
        
        if (index == self.yLabels.count-1) {
            self.lastPoint = point;          //记录最后一个点
        }
        
        
        [self addPoint:point
                 index:index
                isShow:YES
                 value:[valueString floatValue]];
        
        index += 1;
        nextPoint = point;
    }
    
    
    chartLine.path = progressline.CGPath;
    chartLine.strokeColor = UIColorHex(0x4AB2E7).CGColor;
    
    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    pathAnimation.duration = self.yLabels.count*0.4;
    pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
    pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
    pathAnimation.autoreverses = NO;
    [chartLine addAnimation:pathAnimation forKey:@"strokeEndAnimation"];
    
    chartLine.strokeEnd = 1.0;
    

    [bezier1 addLineToPoint:CGPointMake(self.lastPoint.x, kViewHeight)];
    [bezier1 addLineToPoint:CGPointMake(self.originPoint.x, kViewHeight)];
    [bezier1 addLineToPoint:self.originPoint];

    [self addGradientLayer:bezier1];
    
    
    
}


- (void)addPoint:(CGPoint)point index:(NSInteger)index isShow:(BOOL)isHollow value:(CGFloat)value
{
    CGFloat viewWH = 10;
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(5, 5, viewWH, viewWH)];
    view.center = point;
    view.layer.masksToBounds = YES;
    view.layer.cornerRadius = viewWH * 0.5;
    view.layer.borderWidth = 2;
    view.layer.borderColor = UIColorHex(0x4AB2E7).CGColor;
    view.backgroundColor = COLOR_BACKGROUND;
    [self.scrollView addSubview:view];
    
    
    UIButton *coverBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    coverBtn.tag = 100 + index;
    coverBtn.center = point;
    coverBtn.bounds = CGRectMake(0, 0, 20, 20);
    [self.scrollView addSubview:coverBtn];
    [self.scrollView bringSubviewToFront:coverBtn];
    [coverBtn addTarget:self action:@selector(coverAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.coverBtns addObject:coverBtn];
    
    
}


/**
 添加渐变图层
 */
- (void)addGradientLayer:(UIBezierPath *)bezier1
{
    CAShapeLayer *shadeLayer = [CAShapeLayer layer];
    shadeLayer.path = bezier1.CGPath;
    shadeLayer.fillColor = [UIColor greenColor].CGColor;
    
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = CGRectMake(5, 0, 0, kViewHeight - 35);
    gradientLayer.cornerRadius = 5;
    gradientLayer.masksToBounds = YES;
    gradientLayer.colors = @[(__bridge id)[UIColorHex(0x187AC2) colorWithAlphaComponent:0.8].CGColor,(__bridge id)[UIColor.whiteColor colorWithAlphaComponent:0].CGColor];
    gradientLayer.locations = @[@(0.1f),@(1.0f)];
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(1, 1);
    
    CALayer *baseLayer = [CALayer layer];
    [baseLayer addSublayer:gradientLayer];
    [baseLayer setMask:shadeLayer];
    [self.scrollView.layer insertSublayer:baseLayer atIndex:0];
    
    CABasicAnimation *anmi1 = [CABasicAnimation animation];
    anmi1.keyPath = @"bounds";
    anmi1.duration = self.yLabels.count*0.4;
    anmi1.toValue = [NSValue valueWithCGRect:CGRectMake(5, 0, 2 * self.lastPoint.x, kViewHeight - 35)];
    anmi1.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    anmi1.fillMode = kCAFillModeForwards;
    anmi1.autoreverses = NO;
    anmi1.removedOnCompletion = NO;
    
    [gradientLayer addAnimation:anmi1 forKey:@"bounds"];
    
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    UIView *view = [super hitTest:point withEvent:event];
    
        for (UIButton *coverBtn in self.coverBtns){
            CGPoint coverBtnPoint = [coverBtn convertPoint:point fromView:self];
            
            if (CGRectContainsPoint(coverBtn.bounds, coverBtnPoint))
            {
                view = coverBtn;
            }
        }
    
    return view;
}

//点击点
- (void)coverAction:(UIButton *)sender{
    
    
    CMPopTipView *tipView = [self viewWithTag:2019];
    [tipView dismissAnimated:YES];
  
    LZLog(@"%ld",sender.tag);
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 210, 73)];
    
    UIButton *cancelBtn = [UIButton lz_buttonImageName:@"icnon_bai_cancel" backgroundImageName:@""];
    [contentView addSubview:cancelBtn];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(-5);
        make.right.mas_equalTo(-5);
        make.width.height.mas_equalTo(22);
    }];
    
    
   ShellCalculateModel *calculateModel = self.viewModel.dataArray[sender.tag - 100];

    
    UILabel *timeLabel = [UILabel lz_labelWithText:calculateModel.statisticalTime fontSize:k_textFont(16) color:UIColorHex(0xFFFFFF)];
    [contentView addSubview:timeLabel];
    [timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(22);
    }];

    
    ///!!!!:全网算力
    NSString *hashRate = [NSString stringWithFormat:@"%f",calculateModel.hashRate].saveDecimal;
    ///!!!!:交易量
    NSString *tradingAmount = [NSString stringWithFormat:@"%f",calculateModel.tradingAmount].saveDecimal;

    NSArray *dataArray = @[[NSString stringWithFormat:@"%@ %@",LZLocalizedString(@"全网算力"),hashRate],
                        [NSString stringWithFormat:@"%@：%@ USDT",LZLocalizedString(@"全网交易量"),tradingAmount]];


    for (int i = 0; i < dataArray.count; i++){
       UILabel *titleLab = [UILabel lz_labelWithText:dataArray[i] fontSize:k_textFont(12) color:UIColorHex(0xFFFFFF)];
       titleLab.adjustsFontSizeToFitWidth = YES;
       [contentView addSubview:titleLab];
       [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
           make.left.mas_equalTo(0);
           make.top.mas_equalTo(i * 22 + 30);
           make.height.mas_equalTo(17);
           make.width.mas_equalTo(210 - 20);
       }];
    }
    
    
    
    UIColor *backgroundColor = UIColorHex(0x4AB2E7);
    CMPopTipView *popTipView = [[CMPopTipView alloc] initWithCustomView:contentView];
    popTipView.tag = 2019;
    popTipView.hasShadow = NO;
    popTipView.backgroundColor = [backgroundColor colorWithAlphaComponent:0.5];
    [popTipView presentPointingAtView:sender inView:self animated:YES];
    
    [[cancelBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [popTipView dismissAnimated:YES];
    }];
}
#pragma mark - get && set
- (UIScrollView *)scrollView{
    if(!_scrollView){
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator =  NO;
        _scrollView.bounces = NO;
        _scrollView.clipsToBounds = NO;
    }
    return _scrollView;
}


- (NSMutableArray *)coverBtns{
    if(!_coverBtns){
        _coverBtns = [NSMutableArray arrayWithCapacity:0];
    }
    return _coverBtns;
}
@end
